package com.aizuda.boot.modules.business.job;

import com.aizuda.boot.modules.business.permission.domain.entity.RoleDataIsolationEntity;
import com.aizuda.boot.modules.common.constant.enums.PermissionStatusType;
import com.aizuda.boot.modules.common.constant.enums.ValidityType;
import com.aizuda.boot.modules.business.permission.service.RoleDataIsolationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Author sangyirong
 * @ClassName PermissionJob
 * @Version 1.0
 * @Date 2025/7/9 19:21
 */
@Component
@Slf4j
public class PermissionJob {

    @Autowired
    private RoleDataIsolationService roleDataIsolationService;

    /**
     * xxljob权限状态更新定时任务处理器
     * 根据权限的开始时间和结束时间自动更新权限状态
     *
     */
    @XxlJob("permissionStatusHandler")
    public void updatePermissionStatus() {
        log.info("开始执行权限状态更新定时任务");
        
        try {
            Date currentTime = new Date();
            int totalUpdated = 0;
            
            // 1. 处理待生效的权限：开始时间 <= 当前时间，且状态为 UN_ENABLE
            int enabledCount = updateUnEnableToEnable(currentTime);
            totalUpdated += enabledCount;
            log.info("成功将 {} 个待生效权限更新为生效状态", enabledCount);
            
            // 2. 处理已过期的权限：结束时间 < 当前时间，且状态为 ENABLE
            int expiredCount = updateEnableToExpired(currentTime);
            totalUpdated += expiredCount;
            log.info("成功将 {} 个生效中权限更新为已过期状态", expiredCount);
            
            // 3. 处理从待生效直接到已过期的权限：开始时间 <= 当前时间 <= 结束时间，但结束时间 < 当前时间，且状态为 UN_ENABLE
            int directExpiredCount = updateUnEnableToExpired(currentTime);
            totalUpdated += directExpiredCount;
            log.info("成功将 {} 个待生效权限直接更新为已过期状态", directExpiredCount);
            
            log.info("权限状态更新任务执行完成，共更新 {} 条权限记录", totalUpdated);
            
        } catch (Exception e) {
            log.error("权限状态更新任务执行失败：{}", e.getMessage(), e);
        }
    }
    
    /**
     * 将待生效权限更新为生效状态
     * 条件：固定日期权限 && 开始时间 <= 当前时间 && 结束时间 >= 当前时间 && 状态为 UN_ENABLE
     */
    private int updateUnEnableToEnable(Date currentTime) {
        try {
            LambdaUpdateWrapper<RoleDataIsolationEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(RoleDataIsolationEntity::getPermissionStatus, PermissionStatusType.ENABLE)
                         .set(RoleDataIsolationEntity::getUpdatedAt, currentTime)
                         .eq(RoleDataIsolationEntity::getValidityType, ValidityType.FIXED_DATE)
                         .eq(RoleDataIsolationEntity::getPermissionStatus, PermissionStatusType.UN_ENABLE)
                         .le(RoleDataIsolationEntity::getValidityStartDate, currentTime)
                         .ge(RoleDataIsolationEntity::getValidityEndDate, currentTime);
            
            boolean success = roleDataIsolationService.update(updateWrapper);
            return success ? 1 : 0; // 简化返回影响行数统计
        } catch (Exception e) {
            log.error("更新待生效权限为生效状态失败", e);
            return 0;
        }
    }
    
    /**
     * 将生效中权限更新为已过期状态
     * 条件：固定日期权限 && 结束时间 < 当前时间 && 状态为 ENABLE
     */
    private int updateEnableToExpired(Date currentTime) {
        try {
            LambdaUpdateWrapper<RoleDataIsolationEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(RoleDataIsolationEntity::getPermissionStatus, PermissionStatusType.EXPIRED)
                         .set(RoleDataIsolationEntity::getUpdatedAt, currentTime)
                         .eq(RoleDataIsolationEntity::getValidityType, ValidityType.FIXED_DATE)
                         .eq(RoleDataIsolationEntity::getPermissionStatus, PermissionStatusType.ENABLE)
                         .lt(RoleDataIsolationEntity::getValidityEndDate, currentTime);
            
            boolean success = roleDataIsolationService.update(updateWrapper);
            return success ? 1 : 0; // 简化返回影响行数统计
        } catch (Exception e) {
            log.error("更新生效中权限为已过期状态失败", e);
            return 0;
        }
    }
    
    /**
     * 将待生效权限直接更新为已过期状态
     * 条件：固定日期权限 && 结束时间 < 当前时间 && 状态为 UN_ENABLE
     */
    private int updateUnEnableToExpired(Date currentTime) {
        try {
            LambdaUpdateWrapper<RoleDataIsolationEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(RoleDataIsolationEntity::getPermissionStatus, PermissionStatusType.EXPIRED)
                         .set(RoleDataIsolationEntity::getUpdatedAt, currentTime)
                         .eq(RoleDataIsolationEntity::getValidityType, ValidityType.FIXED_DATE)
                         .eq(RoleDataIsolationEntity::getPermissionStatus, PermissionStatusType.UN_ENABLE)
                         .lt(RoleDataIsolationEntity::getValidityEndDate, currentTime);
            
            boolean success = roleDataIsolationService.update(updateWrapper);
            return success ? 1 : 0; // 简化返回影响行数统计
        } catch (Exception e) {
            log.error("更新待生效权限为已过期状态失败", e);
            return 0;
        }
    }
    
    /**
     * 查询需要状态更新的权限列表（用于调试和监控）
     * 
     * @param param 查询参数
     */
    public void queryPermissionStatus(String param) {
        log.info("开始查询权限状态，参数：{}", param);
        
        try {
            Date currentTime = new Date();
            
            // 查询所有固定日期的权限
            LambdaQueryWrapper<RoleDataIsolationEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RoleDataIsolationEntity::getValidityType, ValidityType.FIXED_DATE)
                        .isNotNull(RoleDataIsolationEntity::getValidityStartDate)
                        .isNotNull(RoleDataIsolationEntity::getValidityEndDate);
            
            List<RoleDataIsolationEntity> permissions = roleDataIsolationService.list(queryWrapper);
            
            long waitingCount = 0; // 待生效
            long activeCount = 0;  // 生效中
            long expiredCount = 0; // 已过期
            long needUpdateCount = 0; // 需要更新状态的
            
            for (RoleDataIsolationEntity permission : permissions) {
                PermissionStatusType currentStatus = permission.getPermissionStatus();
                PermissionStatusType expectedStatus = calculateExpectedStatus(permission, currentTime);
                
                // 统计当前状态
                if (currentStatus == PermissionStatusType.UN_ENABLE) waitingCount++;
                else if (currentStatus == PermissionStatusType.ENABLE) activeCount++;
                else if (currentStatus == PermissionStatusType.EXPIRED) expiredCount++;
                
                // 统计需要更新状态的权限
                if (currentStatus != expectedStatus) {
                    needUpdateCount++;
                    log.debug("权限ID：{}，当前状态：{}，应该状态：{}", 
                            permission.getPermissionId(), currentStatus, expectedStatus);
                }
            }
            
            log.info("权限状态统计 - 总数：{}，待生效：{}，生效中：{}，已过期：{}，需要更新：{}", 
                    permissions.size(), waitingCount, activeCount, expiredCount, needUpdateCount);
            
        } catch (Exception e) {
            log.error("查询权限状态失败：{}", e.getMessage(), e);
        }
    }
    
    /**
     * 根据权限的开始时间和结束时间计算期望的权限状态
     */
    private PermissionStatusType calculateExpectedStatus(RoleDataIsolationEntity permission, Date currentTime) {
        if (permission.getValidityType() == ValidityType.PERMANENT) {
            return PermissionStatusType.ENABLE;
        }
        
        Date startDate = permission.getValidityStartDate();
        Date endDate = permission.getValidityEndDate();
        
        if (startDate == null || endDate == null) {
            return PermissionStatusType.ENABLE;
        }
        
        if (currentTime.before(startDate)) {
            return PermissionStatusType.UN_ENABLE; // 待生效
        } else if (currentTime.after(endDate)) {
            return PermissionStatusType.EXPIRED; // 已过期
        } else {
            return PermissionStatusType.ENABLE; // 生效中
        }
    }
}
